package com.zengqingfa.springboot.redis.config;

import com.zengqingfa.springboot.redis.delay.AbstractRedisDelayQueue;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zengqingfa
 * @className RedisDelayQueueConfig
 * @description
 * @create 2022/9/24 18:18
 */
//@Configuration
public class RedisDelayQueueConfig implements InitializingBean {

    /**
     * 可能存在没有实现类的情况
     */
    @Autowired(required = false)
    private List<AbstractRedisDelayQueue> list;

    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (list == null) {
            return;
        }
        //因为是循环监听,核心线程数的大小就是实现AbstractRedisDelayQueue类的子类的数量
        this.threadPoolExecutor = new ThreadPoolExecutor(list.size(), list.size(), 5000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100));
        ;
        //for循环使用线程池，
        list.forEach(d -> {
            threadPoolExecutor.submit(() -> {
                d.listenDelayLoop();
            });
        });
    }
}